package com.edu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.edu.service.OssService;
import com.edu.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
	@Override
	public String uploadFileAvatar(MultipartFile file) {

		//工具类获取值
		String endpoint = ConstantPropertiesUtils.END_POINT;
		String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
		String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
		String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
		try {
			// 创建OSSClient实例。
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

			// 上传文件流
			InputStream inputStream = file.getInputStream();

			String fileName = file.getOriginalFilename();

			//1、在文件名里面添加随机唯一的值
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			fileName = uuid + fileName;

			//2、把文件按照日期进行分类
			String date = new DateTime().toString("yyyy/MM/dd");
			fileName = date+"/"+fileName;

			ossClient.putObject(bucketName, fileName, inputStream);

			// 关闭OSSClient。
			ossClient.shutdown();


			//把需要上传到阿里云oss的路径返回，手动拼接出来
			// https://on-class.oss-cn-guangzhou.aliyuncs.com/%E5%8D%A1%E4%BA%8C.jpeg
			String url = "";
			url = "https://"+bucketName+"."+endpoint+"/"+fileName;

			System.out.println(url);
			return url;

		}catch (Exception e){
			e.printStackTrace();
			return null;
		}

	}
}
